package com.flca.frw.zk.comp;

import java.util.Collection;

import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listbox;
import org.zkoss.zul.Listitem;

import com.flca.frw.zk.helper.ListboxHelper;
import com.flca.frw.zk.util.IListboxProvider;
import com.flca.frw.zk.util.WindowBase;


public class SelectWindowCtrl extends WindowBase {

	private static final long serialVersionUID = 8238274055513196353L;

	private String closeEventName;

	private IListboxProvider provider;
	
	public void setup(IListboxProvider aProvider, String aEventName) 
	{
		provider = aProvider;
		closeEventName = aEventName;
		
		Listbox listbox = getListbox();
		Object todoSearchCriteria = null;
		Collection<?> items = provider.getItems(todoSearchCriteria);
		new ListboxHelper().fillListbox(listbox, items, provider.getPropertyNames(), provider.getLabelNames());
	}
	
	public void onCreate() 
	{
	}
	
	public void onSelect() 
	{
		Button btn = (Button) getComponent("btnSelect");
		btn.setDisabled(false);
	}

	public void onSelectItem() 
	{
		dispatchReadyForClose(true);
	}

	public void onCancel() 
	{
		dispatchReadyForClose(false);
	}
	
	public boolean validate() 
	{
		return true;
	}
	
	@Override
	protected void updateModel() {
		
	}

	@Override
	protected void updateModelFromToView(boolean updateView) {
	}

	@Override
	protected void updateView() {
	}

	public void dispatchReadyForClose(boolean flag) 
	{
		Object data = null;
		if (flag) {
			Listbox listbox = getListbox();
			Listitem selcitem = listbox.getSelectedItem();
			if (selcitem != null) {
				data = selcitem.getAttribute(ListboxHelper.ITEM_KEY);
			}
		}
		Events.sendEvent(new Event(closeEventName, this, data));
	}


	public String getCloseEventName() {
		return closeEventName;
	}

	public void setCloseEventName(String closeEventName) {
		this.closeEventName = closeEventName;
	}	

	private Listbox getListbox() 
	{
		return (Listbox) getFellow("idListbox");
	}

}
